// pages/im/im.js
const app = getApp();
const Hub = require('../../utils/miniProgramSignalr')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hubConnect: null,
    isFullScreen: app.globalData.isFullScreen,
    list: [],
    id: '',
    headImg: '',
    index: 1,
    finished: false,
    lastMsgId: '',
    targetId: '',
    targetHeadImg: '',
    msg: '',
    dsc: '',
    targetName: '',
    groupId: '',
    isGroup: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    wx.hideShareMenu({
      menus: ['shareAppMessage', 'shareTimeline']
    })
    this.setData({
      title: `${options.title}`,
      isGroup: options.isGroup
    })
    
    let that = this
    that.setData({
      id: app.globalData.uid
    })
    that.data.hubConnect = new Hub.HubConnection()
    let obj = {
      appId: 'aK1hI1rE7dE1'
    }
    that.data.hubConnect.start(`${app.socketUrl}chathub`, obj)
    that.data.hubConnect.on('receive', res => {
      console.log(res)
      if( res.isGroup == that.data.isGroup ){
        if( res.extend ){
          res.extend = JSON.parse(res.extend)
        }
        this.data.list.push(res)
        this.setData({
          list: this.data.list,
          lastMsgId: 'item' + res.id,
        })
      }
      // if( res.extend ){
      //   res.extend = JSON.parse(res.extend)
      // }
      // this.data.list.push(res)
      // this.setData({
      //   list: this.data.list,
      //   lastMsgId: 'item' + res.id,
      // })
    })
    that.data.hubConnect.onOpen = res => {
      // console.log(res)
      // console.log("成功开启连接")
      that.data.hubConnect.invoke('Login', app.globalData.uid.toString(),null).then( res => {
        console.log(res)
        if( that.data.isGroup == 1 ){
          console.log(that.data.isGroup)
          that.data.hubConnect.invoke('JoinGroup', options.id).then( res => {
            if( res.code == 1 ){
              that.setData({
                groupId: res.data
              })
              that.getHistory()
            }else{
              wx.showToast({
                title: res.message,
                icon: 'none'
              })
            }
          })
        }else{
          console.log(that.data.isGroup)
          that.setData({
            groupId: options.toid
          })
          that.getHistory()
        }
      })
    }
    // console.log(this.data.isFullScreen);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
    
  },
  send() {
    if (this.data.msg == '') {
      wx.showToast({
        title: '请输入要发送的内容',
        icon: 'none'
      })
      return;
    }
    let that = this
    let list = that.data.list
    let time = that.data.list.length > 0 ? that.data.list[that.data.list.length - 1].sendTime : null
    let extend = {
      headImg: app.globalData.user.HeadImg,
      nickName: app.globalData.user.NickName
    }
    let msg = that.data.msg;
    let type = that.data.isGroup
    console.log(String(app.globalData.uid), that.data.groupId, msg, 0, Number(type), JSON.stringify(extend), time)
    that.data.hubConnect.invoke('send', String(app.globalData.uid), that.data.groupId, msg, 0, Number(type), JSON.stringify(extend), time ).then(res => {
      console.log(res)
      if( res.code == 1 ) {
        res.data.extend = JSON.parse(res.data.extend)
        list.push(res.data)
        that.setData({
          list,
          msg: ''
        })
        that.setData({
          lastMsgId: 'item' + list[list.length - 1].id,
        })
      }else{
        wx.showToast({
          title: '发送失败',
          icon: 'none'
        })
        this.setData({
          msg: ''
        })
      }
    }).catch(res => {
      wx.showToast({
        title: '发送失败',
        icon: 'none'
      })
      this.setData({
        msg: ''
      })
    })
  },
  bindKeyInput(e) {
    this.setData({
      msg: e.detail.value
    })
  },
  goToTest() {
    wx.navigateTo({
      url: `../message/feedback`,
    })
  },
  load() {
    this.getHistory(this.data.targetId)
  },
  upload() {
    var _this = this;
    let time = _this.data.list.length > 0 ? _this.data.list[_this.data.list.length - 1].sendTime : null
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: 'https://wxapp.51xk.info/qiniu/examples/upload_simple_file2.php', //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          success(res) {
            const data = res.data
            // console.log(res);
            if (res) {
              var result = JSON.parse(res.data);
              if (result) {
                if (result.code == '0') {
                  var toID = _this.data.targetId;
                  var fromID = _this.data.id;
                  var msg = result.file;
                  let extend = {
                    headImg: app.globalData.user.HeadImg,
                    nickName: app.globalData.user.NickName
                  }
                  _this.data.hubConnect.invoke('send', String(app.globalData.uid), _this.data.groupId, msg, 1, Number(_this.data.isGroup), JSON.stringify(extend), time ).then(res1 => {
                    res1.data.extend = JSON.parse(res1.data.extend)
                    list.push(res1.data)
                    _this.setData({
                      list: _this.data.list
                    })
                    that.setData({
                      lastMsgId: 'item' + list[list.length - 1].id,
                    })
                  }).catch(() => {
                    wx.showToast({
                      title: '发送失败请稍后重试，或重新进入聊天系统',
                      icon: 'none'
                    })
                  })

                  return;
                }
              }
              wx.showToast({
                title: '上传失败请重试',
                icon: 'none'
              })
            }
            //do something
          }
        })
      }
    })
  },
  getHistory(targetId) {
    console.log(this.data.finished)
    if (this.data.finished) {
      return;
    }
    var that = this;
    wx.request({
			url: `${app.socketUrl}api/message/get_message_list?sender=${String(app.globalData.uid)}&receiver=${that.data.groupId}&index=${Number(that.data.index)}&pageSize=${20}&prevMessageTime=${ that.data.index > 1 ? that.data.list[0].sendTime : '' }&isGroup=${that.data.isGroup}`,
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'appId': 'aK1hI1rE7dE1',
			},
			success: function (res) {
        let list = that.data.list
        if( res.data.code && res.data.data.list.length > 0 ){
          res.data.data.list.forEach( item => {
            if( item.extend ){
              item.extend = JSON.parse(item.extend)
            }
            
          })
          list = res.data.data.list.concat(list)
          that.setData({
            list,
            index: that.data.index + 1,
          })
          if( that.data.index == 2 ){
            that.setData({
              lastMsgId: 'item' + list[list.length - 1].id,
            })
          }
        } else {
          that.setData({
            finished: true
          })
        }
			}
		})
  },
  needSerialize(type) {
    return type == 2 || type == 4 || type == 5 || type == 6;
  },
  preview(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.url,
      urls: [e.currentTarget.dataset.url],
    })
  },
  inputHandler() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})